<?php


namespace PKApp\Log\Classes;


use PKFrame\DataHandler\Arrays;

trait TraitLog
{

    protected function serviceLog(): LogService
    {
        static $cls;
        !empty($cls) ?: $cls = new LogService();
        return $cls;
    }

    protected function serviceOfLogTranslate()
    {
        static $cls;
        !empty($cls) ?: $cls = new LogTranslateService();
        return $cls;
    }

    protected function writeLogByLogin(string $user_name, string $state, string $content = null)
    {
        $this->serviceLog()->CreateLog('login', $user_name, $state, $content);
    }

    protected function checkLastLogin(string $user_name): bool
    {
        $ip = request()->GuestIP();
        $ip_prefix = substr($ip, 0, 4);
        if (in_array($ip_prefix, ['127.', '172.', '192.',]) || substr($ip, 0, 3) == '10.') {
            return true;
        }
        try {
            $area = getLocationByIp($ip, 'city');
            if ($area['city_id'] > 0) {
                $list_area = $this->serviceLog()->GetListOfArea($user_name);
                if (Arrays::Is($list_area)) {
                    $list_area = Arrays::Column($list_area, 'userIPAreaId');
                    return in_array($area['cityId'], $list_area);
                }
            }
        } catch (\Exception $e) {
            handlerException($e);
        }
        return true;
    }

}